import tornado.web
import tornado.ioloop
import tornado.httpclient
from . import utils
import json
import threading
'''
#2.1 翻译接口　异步
    http://ip:port/txt/its
    {
        "id":"",
        "itsType":"", #cnen cnug encn ugcn unkown
        "itsText":"",
        "callbackUrl":""
    }
    resp:
    {
        "ok":1,"failed":}
    }
    {
        "ok":0,"failed":"失败信息"}
    }
    callback:

'''
class txtIts(tornado.web.RequestHandler):

    def work(self, data:dict, inthread = False):
        if inthread:
            print('work:{}'.format(data))
            callbackdata = {
                "id":data['id'],
                "state":{
                    "ok":1,
                    "failed":""
                },
                "result":[
                    {
                        "index":0,
                        "src":"",
                        "target":"",
                        "state":{
                            "ok":1,
                            "failed":None
                        }
                    }
                ]
            }

            http_client = tornado.httpclient.HTTPClient()
            try:
                response = http_client.fetch(data['callbackUrl'], method='POST', body=json.dumps(callbackdata), headers = {'Content-Type': 'application/json'})
            except BaseException as e:
                print(e)

        else:
            t = threading.Thread(target=self.work, args=(data, True))
            t.start()


    def post(self, *args, **kwargs):
        resp = None
        try:
            data=json.loads(self.request.body)
            print(data)
            paramerror = utils.checkParam(data, {
                "id":"",
                "itsType":"", #cnen cnug encn ugcn unkown
                "itsText":"",
                "callbackUrl":""
            })
            if paramerror == '':
                self.work(data)
                resp = {
                    "ok":1,"failed":''
                }
            else:
                resp = {
                    "ok":0,"failed": paramerror
                }

        except BaseException as e:
            resp = {
                "ok":0,"failed": str(e)
            }

        self.write(resp)
